package com.tckj.boot.modules.web.admin;

import com.tckj.boot.modules.domain.obj.category.application.CategoryService;
import com.tckj.boot.modules.domain.obj.category.model.Category;
import com.tckj.boot.modules.domain.obj.category.model.CategoryRespository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

/**
 * @ClassName AdminCategoryController
 * @Description
 * @Author icodebug
 * @Date 19-6-19 下午2:14
 */
@RestController
@RequestMapping("/admin/category")
public class AdminCategoryController {

    @Autowired
    private CategoryRespository respository;
    @Autowired
    private CategoryService service;

    @GetMapping("/tree")
    public ResponseEntity getTree(){
        return ResponseEntity.ok(service.getAllTreeData());
    }

    @GetMapping
    public ResponseEntity get(Long pid){
        if (pid==null){
            return  ResponseEntity.ok(respository.findAll(Sort.by(Sort.Direction.ASC,"sort")));
        }else return ResponseEntity.ok(respository.findByParent(respository.findById(pid).get(),Sort.by(Sort.Direction.ASC,"sort")));
    }

    @PostMapping
    public ResponseEntity add(@RequestBody Category category){
//        if (category.getParent()!=null&&category.getParent().getId()!=null){
//            category.setParent(respository.getOne(category.getParent().getId()));
//        }
        //todo 排序问题回头再优化吧！
        return ResponseEntity.ok(respository.saveAndFlush(category));
    }

}
